package com.example.knowman.controller;


import com.example.knowman.ReturnMessage.MExKnowMain9_5BackAD;
import com.example.knowman.ReturnMessage.MExKnowMain9_5BackKC;
import com.example.knowman.ReturnMessage.MExKnowMain9_5rank;
import com.example.knowman.ReturnMessage.Message;
import com.example.knowman.dao.knowMainEx9_5BackKnowCategory;
import com.example.knowman.dao.knowMainEx9_5BackarchDept;
import com.example.knowman.dao.knowMainEx9_5ByPeriod;
import com.example.knowman.entity.archDept;
import com.example.knowman.entity.knowCategory;
import com.example.knowman.entity.knowMain;
import com.example.knowman.entity.staffList;
import com.example.knowman.service.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

//9.5排行榜
@RestController
@RequestMapping("/RankingList")
public class RankingListController {
    private final IKnowMainService iknowMainService;

    private final IKnowCategoryService iKnowCategoryService;

    private final IStaffListService iStaffListService;

    private final IArchDeptService iArchDeptService;

    private final ILog4operateService iLog4operateService;

    public RankingListController(IKnowMainService iknowMainService, IStaffListService iStaffListService, IKnowCategoryService iKnowCategoryService,
                                 IArchDeptService iArchDeptService,ILog4operateService iLog4operateService) {
        this.iknowMainService = iknowMainService;
        this.iStaffListService = iStaffListService;
        this.iKnowCategoryService = iKnowCategoryService;
        this.iArchDeptService = iArchDeptService;
        this.iLog4operateService = iLog4operateService;
    }


//    //9.5返回员工以及知识数等信息,关键字（部门名ArchDeptName，知识体系KnowCateName，时间段createTime,TimeType:全部，按年，按月，按日,全=0，年=1，月=2，日=3）
    @GetMapping("getTable")
    public ResponseEntity<MExKnowMain9_5rank> getTable(@RequestParam(required = false) String ArchDeptName,
                                                       @RequestParam String KnowCateName,
                                                       @RequestParam Integer TimeType,
                                                       @RequestParam(required = false) String period) {

        //根据ArchDeptName返回List<员工姓名、员工工号、部门名ArchDeptName（毕竟这一项可能是全部）>  staffList表
        List<staffList> sfL = iStaffListService.listByDeptName(ArchDeptName);

//        System.out.println(sfL);


        //根据KnowCateName返回List<knowCateId>,包括该类的id和下面小类以及小类的小类的id
        String KCN = null;
        List<knowCategory> kcL = new ArrayList<>();
        if(KnowCateName.equals("全部")){
            kcL = iKnowCategoryService.listByKnowCateName(KCN);
        }
        else{
            kcL = iKnowCategoryService.listByKnowCateName(KnowCateName);
        }

//        System.out.println(kcL);

        List<knowMain> forSum = iknowMainService.getForSum(TimeType,period);
//        System.out.println(forSum);
        //遍历员工，二级遍历List<knowCateId>，时间段，得到count数量，累加
            //判断timeType

        List<knowMainEx9_5ByPeriod> KCLres = new ArrayList<>();
        for(staffList item: sfL){
            knowMainEx9_5ByPeriod temp = new knowMainEx9_5ByPeriod();
            temp.setStaffCode(item.getStaffCode());
            temp.setPeriod(period);
            temp.setStaffName(item.getStaffName());
            temp.setKnowCateName(KnowCateName);
            temp.setArchDeptName(item.getArchDeptName());
//            System.out.println(temp);
//            Integer sum = iknowMainService.getCount(temp,kcL,TimeType);
//                System.out.println(sum);
            Integer sum = 0;
            for(knowCategory kclItem:kcL){
                for(knowMain kmitem:forSum){
                    if (kmitem.getKnowCateId()== kclItem.getKnowCateId() && kmitem.getStaffCode().equals(temp.getStaffCode())){
                        sum++;
                    }
                }
            }

            if(TimeType == 0 ){
                temp.setPeriod("不限");
            }
            temp.setSum(sum);
//                System.out.println(temp);
            if(sum > 0 ){
                KCLres.add(temp);
            }
        }

        //KCLres之后得排序，排序后填入rank属性
        KCLres.sort((o1, o2) -> o2.getSum().compareTo(o1.getSum()));
        Integer flag = 1;
        for (knowMainEx9_5ByPeriod item:KCLres){
            item.setRank(flag);
            flag++;
        }
        //填写message
        MExKnowMain9_5rank mes = new MExKnowMain9_5rank();
        mes.setCode(200);
        mes.setTip("查找成功");
        mes.setList(KCLres);

        return ResponseEntity.ok(mes);
    }


    //9.5 列出有哪些部门,返回archDept表中的List<部门code和部门名>
    @GetMapping("getArchDept")
    public ResponseEntity<MExKnowMain9_5BackAD> getAD() {

        List<archDept> list = iArchDeptService.showAll();
        List<knowMainEx9_5BackarchDept> res = new ArrayList<>();

        for(archDept item : list){
            knowMainEx9_5BackarchDept temp = new knowMainEx9_5BackarchDept();
            temp.setArchDeptId(item.getArchDeptId());
            temp.setArchDeptCode(item.getArchDeptCode());
            temp.setArchDeptName(item.getArchDeptName());

            res.add(temp);
        }

        MExKnowMain9_5BackAD mes = new MExKnowMain9_5BackAD();
        mes.setCode(200);
        mes.setTip("查找成功");
        mes.setList(res);


        return ResponseEntity.ok(mes);

    }


    //9.5列出有哪些知识体系，全部（一级二级三级全都要）都列出来，返回knowCategory中的List<knowCateId,cateId,knowCateName>
    @GetMapping("getKnowCategory")
    public ResponseEntity<MExKnowMain9_5BackKC> getKnowCategory() {

        List<knowCategory> list = iKnowCategoryService.showAll();
        List<knowMainEx9_5BackKnowCategory> res = new ArrayList<>();

        for(knowCategory item : list){
            knowMainEx9_5BackKnowCategory temp = new knowMainEx9_5BackKnowCategory();
            temp.setCateId(item.getCateId());
            temp.setKnowCateId(item.getKnowCateId());
            temp.setKnowCateName(item.getKnowCateName());

            res.add(temp);
        }

        MExKnowMain9_5BackKC mes = new MExKnowMain9_5BackKC();
        mes.setCode(200);
        mes.setTip("查找成功");
        mes.setList(res);


        return ResponseEntity.ok(mes);

    }


    //9.5将getTable导出excel
    @GetMapping("export")
    public ResponseEntity<Message> export(@RequestParam(required = false) String ArchDeptName,
                                          @RequestParam String KnowCateName,
                                          @RequestParam Integer TimeType,
                                          @RequestParam(required = false) String period,
                                          HttpServletResponse response) {

        //根据ArchDeptName返回List<员工姓名、员工工号、部门名ArchDeptName（毕竟这一项可能是全部）>  staffList表
        List<staffList> sfL = iStaffListService.listByDeptName(ArchDeptName);

//        System.out.println(sfL);


        //根据KnowCateName返回List<knowCateId>,包括该类的id和下面小类以及小类的小类的id
        String KCN = null;
        List<knowCategory> kcL = new ArrayList<>();
        if(KnowCateName.equals("全部")){
            kcL = iKnowCategoryService.listByKnowCateName(KCN);
        }
        else{
            kcL = iKnowCategoryService.listByKnowCateName(KnowCateName);
        }

//        System.out.println(kcL);
        List<knowMain> forSum = iknowMainService.getForSum(TimeType,period);

        //遍历员工，二级遍历List<knowCateId>，时间段，得到count数量，累加
        //判断timeType

        List<knowMainEx9_5ByPeriod> KCLres = new ArrayList<>();
        for(staffList item: sfL){
            knowMainEx9_5ByPeriod temp = new knowMainEx9_5ByPeriod();
            temp.setStaffCode(item.getStaffCode());
            temp.setPeriod(period);
            temp.setStaffName(item.getStaffName());
            temp.setKnowCateName(KnowCateName);


            temp.setArchDeptName(item.getArchDeptName());

            Integer sum = 0;
            for(knowCategory kclItem:kcL){
                for(knowMain kmitem:forSum){
                    if (kmitem.getKnowCateId()== kclItem.getKnowCateId() && kmitem.getStaffCode().equals(temp.getStaffCode())){
                        sum++;
                    }
                }
            }

            if(TimeType == 0 ){
                temp.setPeriod("不限");
            }
            temp.setSum(sum);
//                System.out.println(temp);
            if(sum > 0 ){
                KCLres.add(temp);
            }
        }

        //KCLres之后得排序，排序后填入rank属性
        KCLres.sort((o1, o2) -> o2.getSum().compareTo(o1.getSum()));
        Integer flag = 1;
        for (knowMainEx9_5ByPeriod item:KCLres){
            item.setRank(flag);
            flag++;
        }

        //导出excel
        XSSFWorkbook ExcelOut = new XSSFWorkbook();
        Sheet sheet =ExcelOut.createSheet("排行榜");

        Row titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("列");//第一列
        titleRow.createCell(1).setCellValue("序号");
        titleRow.createCell(2).setCellValue("知识体系");
        titleRow.createCell(3).setCellValue("发布时间");
        titleRow.createCell(4).setCellValue("部门名称");
        titleRow.createCell(5).setCellValue("员工姓名");
        titleRow.createCell(6).setCellValue("发布数量");

        int cell = 1;
        for (knowMainEx9_5ByPeriod item : KCLres){
            Row row =sheet.createRow(cell);
            row.createCell(0).setCellValue(cell);
            row.createCell(1).setCellValue(item.getRank());//将数据库的数据遍历出来
            row.createCell(2).setCellValue(item.getKnowCateName());
            row.createCell(3).setCellValue(item.getPeriod());
            row.createCell(4).setCellValue(item.getArchDeptName());//将数据库的数据遍历出来
            row.createCell(5).setCellValue(item.getStaffName());
            row.createCell(6).setCellValue(item.getSum());
            cell++;
        }

        String fileName ="知识分享排行榜.xlsx";
        OutputStream outputStream =null;
        try {
            fileName = URLEncoder.encode(fileName,"UTF-8");
            //设置ContentType请求信息格式
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            outputStream = response.getOutputStream();
            ExcelOut.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //log4
//        if((operator!=null && !operator.isEmpty()) && (ipAddress!=null && !ipAddress.isEmpty())){
//            String content = operator+"导出了知识排行榜";
//            iLog4operateService.insertSingle(operator,content,ipAddress);
//        }
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request1 = attributes.getRequest();
        String ipAddress=request1.getHeader("ip");
        String operator=request1.getHeader("staffCode");
        String content = operator+"导出了知识排行榜";
        iLog4operateService.insertSingle(operator,content,ipAddress);
        //
        
        //填写message
        Message mes = new Message();
        mes.setCode(200);
        mes.setTip("导出成功");


        return ResponseEntity.ok(mes);
    }

}
